package cn.com.company.main.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.SQLQuery;
import org.hibernate.Session;

import cn.com.company.main.client.entity.TItem;
import cn.com.company.main.dao.BaseHibernateDAO;

public class DataAccessServlet extends HttpServlet {

	private static final long serialVersionUID = 544479849308939811L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doSomething(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doSomething(req, resp);
	}

	@SuppressWarnings("unused")
	public void doSomething(HttpServletRequest req, HttpServletResponse resp) {
		BaseHibernateDAO dao = new BaseHibernateDAO();
		Session session = dao.getSession();
		String op = req.getParameter("op");
		String key = req.getParameter("key");
		if(true){//TODO TEST ONLY
			return;
		}
		if("auto".equals(op)){
			StringBuffer json = new StringBuffer();
			String sql = "select {0} from t_item where fname <>'*' ";
			if(key != null && !"".equals(key)){
				sql += " and (fnumber like '%" + key + "%' ";
				sql += " or fname like '%" + key + "%') ";
			}
			SQLQuery query = session.createSQLQuery(sql.replace("{0}", "*"));
			query.addEntity(TItem.class);
			@SuppressWarnings("unchecked")
			List<TItem> list = query.list(); 
			
			query = session.createSQLQuery(sql.replace("{0}", "count(*)"));
			Object count = query.uniqueResult();
			int totalCount = Integer.parseInt(count+"");
					
			json.append("{\"totalCount\":\""+totalCount+"\",\"topics\":[");
			for(TItem item: list){
				json.append("{\"fname\":\""+item.getFname()+"\",\"fnumber\":\""+item.getFnumber()+"\"},");
			}
			String jsonString = json.toString();
			if(jsonString.endsWith(",")){
				jsonString = jsonString.substring(0,jsonString.length()-1);
			}
			jsonString += "]}";
			System.out.print(jsonString);
			try {
				resp.getOutputStream().write(jsonString.getBytes("gb2312"));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
